package cn.gs.meta.ops;

// @author gs
import cn.gs.common.meta.ModelBaseShow;
import cn.gs.meta.db.tables.ModelBase;
import cn.gs.meta.db.tables.Obj;
import cn.gs.meta.db.tables.Ogn;
import cn.gs.util.HibernateUtil;
import java.util.Collection;
import java.util.Date;
import org.hibernate.Query;

public class ModelBaseOps {

    public static ModelBaseShow get(int id) {
        ModelBase model = getById(id);
        ModelBaseShow show = new ModelBaseShow();
        show.setId(model.getId());
        show.setName(model.getName());
        if (model instanceof Ogn) {
            show.setIsOgn(true);
        } else if (model instanceof Obj) {
            show.setIsObj(true);
        } else {
            //TODO: else
        }
        return show;
    }

    public static ModelBase getById(int id) {
        return (ModelBase) HibernateUtil.getSession().get(ModelBase.class, id);
    }

    public static ModelBase getByName(String name) {
        Query query = HibernateUtil.getSession().createQuery("from ModelBase where name=:name").setParameter("name", "'" + name + "'");
        return (ModelBase) query.uniqueResult();
    }

    public static ModelBase getBySch(String sch) {
        Query query = HibernateUtil.getSession().createQuery("from ModelBase where sch like :sch").setParameter("sch", "'" + sch + "'");
        return (ModelBase) query.uniqueResult();
    }

    public static Collection<ModelBase> search(String sch, int rows) {
        Query query = HibernateUtil.getSession().createQuery("from ModelBase where sch like :sch").setParameter("sch", "'" + sch + "'").setMaxResults(rows);
        return query.list();
    }

    public static void save(ModelBase model) {
        model.setModifiedTime(new Date(System.currentTimeMillis()));
        HibernateUtil.getSession().saveOrUpdate(model);
    }

    public static void delete(ModelBase model) {
        HibernateUtil.getSession().delete(model);
    }
}
